import libtcodpy as libtcod
import utils
from collections import deque
from dialog import get_dialog

MAX_MSG_LEN = utils.MAP_RECT[2] - 2

#===============================================================================
# HUD
#===============================================================================
class Hud:
    def __init__(self, game):
        self.game = game
        self.player_data = game.player_data
        
        self.message_queue = deque([])
        self.current_message = ''
        self.get_current_message = True
        self.num_added = 0
        
        self.show_monster_stats = None
        
    def add_message(self, *strings):
        next = False
        if len(self.message_queue) == 0 and self.num_added < 1:
            next = True
        for s in strings:
            if len(s) <= MAX_MSG_LEN:
                self.message_queue.append(s)
                self.num_added += 1
            else:
                utils.write_error('Message "%s" longer than %d characters' % (str, MAX_MSG_LEN))
        if next:
            self.next_message()
    
    def next_message(self):
        if len(self.message_queue) > 0:
            self.current_message = self.message_queue.popleft()
            
    def clear_queue(self):
        self.message_queue.clear()
    
    def print_str(self, x, y, str, align = 0, background = libtcod.BKGND_SET):
        if align == 0:
            libtcod.console_print_ex(0, utils.HUD_RECT[0] + 1 + x, utils.HUD_RECT[1] + 2 + y, background, libtcod.LEFT, str)
        elif align == 1:
            libtcod.console_print_ex(0, utils.HUD_RECT[0] + 1 + x, utils.HUD_RECT[1] + 2 + y, background, libtcod.CENTER, str)
        else:
            libtcod.console_print_ex(0, utils.HUD_RECT[0] + 1 + x, utils.HUD_RECT[1] + 2 + y, background, libtcod.RIGHT, str)
            
    def print_bar(self, x, y, width, val, max, col1, col2, col3):
        x = utils.HUD_RECT[0] + 1 + x
        y = utils.HUD_RECT[1] + 2 + y
        for i in range(0, width):
            if float(i) / float(width) < float(val) / float(max):
                libtcod.console_set_back(0, x + i, y, col2, libtcod.BKGND_SET)
            else:
                libtcod.console_set_back(0, x + i, y, col1, libtcod.BKGND_SET)
                
        libtcod.console_set_foreground_color(0, col3)
        libtcod.console_print_ex(0, x + width / 2, y, libtcod.BKGND_NONE, libtcod.CENTER, str(val) + '/' + str(max))
        libtcod.console_set_foreground_color(0, utils.COLORS['FCOL'])
        
    def print_monster_stats(self, monster):
        self.show_monster_stats = monster
        
    def draw(self):
        self.num_added = 0
              
        #Sidebar
        libtcod.console_print_frame(0, utils.HUD_RECT[0], utils.HUD_RECT[1], utils.HUD_RECT[2], utils.HUD_RECT[3], False, libtcod.BKGND_SET, self.player_data['name'])
        self.print_str(0, 0, 'Level: ' + str(self.player_data['level']))
        self.print_str(0, 1, 'HP:')
        self.print_bar(3, 1, 10, self.player_data['hp'], self.player_data['max_hp'], libtcod.desaturated_red, libtcod.red, libtcod.white)
        self.print_str(0, 2, 'XP:')
        self.print_bar(3, 2, 10, self.player_data['xp'], self.player_data['next_lvl'], libtcod.desaturated_blue, libtcod.blue, libtcod.white)
        self.print_str(0, 3, 'Attack: ' + str(self.player_data['attack']))
        self.print_str(0, 4, 'Defense: ' + str(self.player_data['defense']))
        self.print_str(0, 5, 'Depth: ' + str(self.game.current_depth + 1))
        
        #Last Message
        libtcod.console_print(0, utils.HUD_RECT[2] + 1, utils.HUD_RECT[1], self.current_message)
        if len(self.message_queue) > 0:
            libtcod.console_set_foreground_color(0, libtcod.black)
            libtcod.console_set_background_color(0, libtcod.white)
            libtcod.console_print_ex(0, utils.SCREEN_WIDTH - 1, utils.HUD_RECT[1], libtcod.BKGND_SET, libtcod.RIGHT, 'SPACE')
            libtcod.console_set_foreground_color(0, utils.COLORS['FCOL'])
            libtcod.console_set_background_color(0, utils.COLORS['BCOL'])
            
        #Monster Stats
        if self.show_monster_stats != None:
            libtcod.console_set_foreground_color(0, libtcod.black)
            libtcod.console_set_background_color(0, libtcod.white)
            self.print_str(13 / 2, 7, self.show_monster_stats.name, 1)
            libtcod.console_set_foreground_color(0, utils.COLORS['FCOL'])
            libtcod.console_set_background_color(0, utils.COLORS['BCOL'])
            
            self.print_str(0, 8, 'HP:')
            self.print_bar(3, 8, 10, self.show_monster_stats.hp, self.show_monster_stats.max_hp, libtcod.desaturated_red, libtcod.red, libtcod.white)
            
            self.show_monster_stats = None

#===============================================================================
# HELP SCREEN            
#===============================================================================
class Help(object):
    def __init__(self, game):
        self.game = game
        self.show = False
        
    def display(self):
        self.show = True
            
    def hide(self):
        self.show = False
    
    def draw(self):
        if self.show:
            libtcod.console_clear(0)
            libtcod.console_print(0, 1, 1, 'This is the help screen, nigga. Press any key to leave.')
            
#===============================================================================
# INVENTORY
#===============================================================================
class Inventory(object):
    def __init__(self, game):
        self.game = game
        self.show = False
        self.action = 'Inventory'
        self.player_data = game.player_data
        self.items = self.player_data['inventory']
        self.equipment = self.player_data['equipment']
        
    def display(self, action = None):
        if action == None:
            self.action = 'Inventory'
        else:
            self.action = action
        self.show = True
            
    def hide(self):
        self.show = False
        
    def add_item(self, item):
        self.items.append(item)
        self.items.sort(key = lambda i: i.action_key)
        
    def remove_item(self, item):
        if item.equipped:
            self.equip_item(item)
        self.items.remove(item)
        
    def equip_item(self, item):
        if item.type == 'weapon' or item.type == 'shield' or item.type == 'ring':
            if item.equipped:
                if item.type == 'ring':
                    if self.equipment['rings']['left'] == item:
                        self.equipment['rings']['left'] = None
                    elif self.equipment['rings']['right'] == item:
                        self.equipment['rings']['right'] = None
                else:
                    self.equipment[item.type] = None
                    
                self.player_data['defense'] -= item.defense
                self.player_data['attack'] -= item.attack
                
                item.equipped = False
                item.add_dialog('unequip', item.name)
            else:
                if item.requirement > self.player_data['level']:
                    item.add_dialog('more_xp', item.name)
                else:
                    if item.type == 'ring':
                        if self.equipment['rings']['left'] == None:
                            item.equipped = True
                            item.add_dialog('equip', item.name)
                            self.equipment['rings']['left'] = item
                        elif self.equipment['rings']['right'] == None:
                            item.equipped = True
                            item.add_dialog('equip', item.name)
                            self.equipment['rings']['right'] = item
                        else:
                            item.add_dialog('already_equipped', 2, 'rings')
                    else:
                        if self.equipment[item.type] == None:
                            item.equipped = True
                            item.add_dialog('equip', item.name)
                            self.equipment[item.type] = item
                        else:
                            item.add_dialog('already_equipped', 1, item.type)
                            
                    self.player_data['defense'] += item.defense
                    self.player_data['attack'] += item.attack
        else:
            item.add_dialog('not_equippable', item.name)
        
    def draw(self):
        if self.show:
            strings = []
            max_length = len(self.action) + 4
            for i, item in enumerate(self.player_data['inventory']):
                
                if item.equipped:
                    s = get_dialog('item', item.action_key, '(e)' + item.name)
                else:
                    s = get_dialog('item', item.action_key, item.name)
                strings.append(s)
                if len(s) + 2 > max_length:
                    max_length = len(s) + 2
            libtcod.console_print_frame(0, utils.SCREEN_WIDTH - max_length, 0, max_length, len(strings) + 2, True, libtcod.BKGND_SET, self.action)
            for i, str in enumerate(strings):
                libtcod.console_print(0, utils.SCREEN_WIDTH - max_length + 1, i + 1, str)

#===============================================================================
# DEATH SCREEN                
#===============================================================================
class Death(object):
    def __init__(self):
        pass
    
    def draw(self):
        libtcod.console_clear(0)
        libtcod.console_print_ex(0, utils.SCREEN_WIDTH / 2, utils.SCREEN_HEIGHT / 2, libtcod.BKGND_SET, libtcod.CENTER, 'You died!')
        libtcod.console_print_ex(0, utils.SCREEN_WIDTH / 2, utils.SCREEN_HEIGHT / 2 + 1, libtcod.BKGND_SET, libtcod.CENTER, 'Press any key to exit...')
        libtcod.console_flush()
        libtcod.console_wait_for_keypress(True)

if __name__ == "__main__":
    print "Please run main.py!"
